# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
@Author : Ayao
@Time   : 2022/5/22
@File   : 翻转字符串里的单词.py
"""


class Solution:
    # 反转字符串
    def reverseString(self, s):
        left, right = 0, len(s) - 1
        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1
        return s

    def reverseWords(self, s: str):
        lens = len(s)
        res = []
        left, right = 0, lens - 1
        while left < right and s[left] == " ":
            left += 1
        while left < right and s[right] == " ":
            right -= 1
        while left <= right:
            if s[left] != " ":
                res.append(s[left])
            elif s[left] == " " and res[-1] != " ":
                res.append(s[left])
            left += 1

        res = self.reverseString(res)

        left, right = 0, 0
        while left < len(res):
            while right < len(res) and res[right] != " ":
                right += 1
            res[left:right] = self.reverseString(res[left:right])
            left = right + 1
            right += 1
        str_end = ""

        for i in res:
            str_end += i
        return str_end


if __name__ == '__main__':
    # s = " an good  exe "
    s = "the sky is blue"
    # s = " a good   example  "
    res = Solution().reverseWords(s)
    print(res)
